package com.stxx.assistant.framwork.utils.dbmeta;

import cn.hutool.core.util.StrUtil;
import org.noear.solon.annotation.Component;

/**
 * @author Fuzhenlei
 * @date 2025/01/14 11:57
 */
@Component
public class PostgresqlMeta implements DbMeta{

    @Override
    public String getTableSql(String schema) {
        return "SELECT\n" +
                "  c.relname AS table_name,\n" +
                "  col_description(c.oid, 0) table_comment\n" +
                "FROM pg_class c\n" +
                "JOIN  pg_namespace n ON n.oid = c.relnamespace\n" +
                "LEFT JOIN pg_inherits i ON i.inhrelid = c.oid\n" +
                "WHERE c.relkind in ('r','p')\n" +
                "AND i.inhrelid IS NULL\n" +
                "and n.nspname='"+schema+"'";
    }

    @Override
    public String getColumnSql(String schema, String tableName) {
        return "select \n" +
                "a.attname column_name\n" +
                ",t.typname data_type\n" +
                ",case when r.conname is null then 0 else 1 end is_pk\n" +
                ",coalesce(ic.CHARACTER_MAXIMUM_LENGTH,ic.NUMERIC_PRECISION) len\n" +
                ",ic.NUMERIC_SCALE decimals\n" +
                ",col_description(c.oid,a.attnum) column_comment\n" +
                "from pg_class c\n" +
                "join pg_attribute a on a.attrelid=c.oid\n" +
                "join pg_type t on t.oid = a.atttypid\n" +
                "join information_schema.columns ic on ic.table_name=c.relname and ic.column_name=a.attname\n" +
                "left join pg_constraint r on r.conrelid =c.oid and r.contype = 'p' and a.attnum = r.conkey[1]\n" +
                "WHERE\n" +
                " a.attnum>0\n" +
                "and ic.table_schema='"+schema+"'"+
                "and c.relname = '"+tableName+"'\n";
    }

    @Override
    public String getJavaType(String type) {
        if(StrUtil.containsAnyIgnoreCase(type,"int","")){
            return "int";
        }else if(StrUtil.containsAnyIgnoreCase(type,"numeric","decimal","float")){
            return "decimal";
        }else if(StrUtil.containsAnyIgnoreCase(type,"boolean")){
            return "bool";
        }else if(StrUtil.containsAnyIgnoreCase(type,"date","timestamp")){
            return "datetime";
        }
        return "string";
    }
    @Override
    public String getDbName() {
        return "POSTGRESQL";
    }
}
